package com.fmx.BookStore.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fmx.BookStore.domain.Permission;
import com.fmx.BookStore.mapper.PermissionMapper;
import com.fmx.BookStore.service.IPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper,Permission>implements IPermissionService {
    @Autowired
    PermissionMapper permissionMapper;
    @Override
    public Permission selectPermissionById(Long permissionId) {
        return permissionMapper.selectPermissionById(permissionId);
    }

    @Override
    public List<Permission> listPermission(Permission permission) {
        return permissionMapper.listPermission(permission);
    }

    @Override
    public int insertPermission(Permission permission) {
        return permissionMapper.insertPermission(permission);
    }

    @Override
    public int updatePermission(Permission permission) {
        return permissionMapper.updatePermission(permission);
    }

    @Override
    public int deletePermission(Long permissionId) {
        return permissionMapper.deletePermission(permissionId);
    }

    @Override
    public List<Permission> findMenus(String name) {
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("sort_num");
        if (StrUtil.isNotBlank(name)) {
            queryWrapper.like("permission_name", name);
        }
        // 查询所有数据
        List<Permission> list = list(queryWrapper);
        // 找出pid为0的一级菜单
        List<Permission> parentNodes = list.stream().filter(menu -> menu.getPid() == 0).collect(Collectors.toList());
        // 找出一级菜单的子菜单
        for (Permission permission : parentNodes) {
            // 筛选所有数据中pid=父级id的数据就是二级菜单
            permission.setChildren(list.stream().filter(m -> permission.getPermissionId().equals(m.getPid())).collect(Collectors.toList()));
        }
        return parentNodes;
    }
}
